'use client'

import React, { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { Save, Lock, Eye, EyeOff, AlertCircle, CheckCircle, Database } from 'lucide-react'
import { useDeviceInstanceParameters } from '@/hooks/use-device-instance-parameters'
import { useAuth } from '@/hooks/use-auth'
import { useToast } from '@/hooks/use-toast'

interface ParameterEntryDialogProps {
  tableName: string
  instanceId: number
  deviceName: string
  tableType: string
  classificationCode: string
  onSave?: () => void
}

export function ParameterEntryDialog({
  tableName,
  instanceId,
  deviceName,
  tableType,
  classificationCode,
  onSave
}: ParameterEntryDialogProps) {
  const [saving, setSaving] = useState(false)
  const [showAllFields, setShowAllFields] = useState(false)
  const [selectedSpecialty, setSelectedSpecialty] = useState<string>('all')
  const { toast } = useToast()

  console.log('=== ParameterEntryDialog 初始化 ===')
  console.log('接收到的参数:', {
    tableName,
    instanceId,
    deviceName,
    tableType,
    classificationCode
  })

  const {
    fields,
    loading,
    error,
    editData,
    user,
    permissions,
    updateFieldValue,
    saveParameters,
    getFieldsByDataSource,
    getEditableFieldsCount,
    getVisibleFieldsCount,
    getUserDataSources,
    getRequiredFieldsCount,
    getFilledRequiredFieldsCount,
    getMissingRequiredFields,
    canEditField
  } = useDeviceInstanceParameters(tableName, instanceId, classificationCode)

  console.log('=== ParameterEntryDialog 调试信息 ===');
  console.log('表名:', tableName);
  console.log('实例ID:', instanceId);
  console.log('设备名:', deviceName);
  console.log('表类型:', tableType);
  console.log('分类码:', classificationCode);
  console.log('字段数据:', fields);
  console.log('加载状态:', loading);
  console.log('错误信息:', error);
  console.log('用户信息:', user);
  console.log('权限信息:', permissions);

  const { hasDataSourceAccess } = useAuth(tableName)

  const handleSave = async () => {
    try {
      setSaving(true)
      const result = await saveParameters()
      
      if (result.missingFields && result.missingFields.length > 0) {
        // 有缺失的必填字段，显示警告信息
        toast({
          title: "保存成功（部分完成）",
          description: `参数已保存，但以下必填字段尚未填写：${result.missingFields.join('、')}`,
          variant: "default",
        })
      } else {
        // 所有必填字段都已填写
        toast({
          title: "保存成功",
          description: "参数已成功保存",
        })
      }
      onSave?.()
    } catch (error) {
      console.error('保存失败:', error)
      toast({
        title: "保存失败",
        description: error instanceof Error ? error.message : "保存参数失败",
        variant: "destructive",
      })
    } finally {
      setSaving(false)
    }
  }

  const getDataSourceName = (source: string) => {
    const names: Record<string, string> = {
      'P': '采购',
      'E': '设计',
      'M': '制造',
      'O': '运维',
      'C': '施工',
      'R': '运行'
    }
    return names[source] || source
  }

  const getTableTypeName = (type: string) => {
    const names: Record<string, string> = {
      'naming': '命名信息表',
      'position': '位置信息表',
      'base': '基础参数表'
    }
    return names[type] || type
  }

  const getDataSourceColor = (source: string) => {
    const colors: Record<string, string> = {
      'P': 'bg-blue-100 text-blue-800',
      'E': 'bg-green-100 text-green-800',
      'M': 'bg-orange-100 text-orange-800',
      'O': 'bg-purple-100 text-purple-800',
      'C': 'bg-yellow-100 text-yellow-800',
      'R': 'bg-red-100 text-red-800'
    }
    return colors[source] || 'bg-gray-100 text-gray-800'
  }

  if (loading) {
    return (
      <div className="space-y-4">
        <div className="text-center p-4">
          <div className="text-sm text-gray-600 mb-2">加载参数表: {tableName}</div>
        </div>
        <div className="animate-pulse">
          <div className="h-8 bg-gray-200 rounded w-1/3 mb-4"></div>
          <div className="space-y-3">
            {[1, 2, 3, 4, 5].map(i => (
              <div key={i} className="h-16 bg-gray-200 rounded"></div>
            ))}
          </div>
        </div>
      </div>
    )
  }

  if (error) {
    return (
      <Alert variant="destructive">
        <AlertCircle className="h-4 w-4" />
        <AlertDescription>
          <div>
            <div>{error}</div>
            <div className="text-xs mt-2 opacity-70">
              表名: {tableName} | 实例ID: {instanceId} | 设备名: {deviceName}
            </div>
          </div>
        </AlertDescription>
      </Alert>
    )
  }

  const userDataSources = getUserDataSources()
  const editableCount = getEditableFieldsCount()
  const visibleCount = getVisibleFieldsCount()
  const requiredFieldsCount = getRequiredFieldsCount()
  const filledRequiredFieldsCount = getFilledRequiredFieldsCount()
  const missingRequiredFields = getMissingRequiredFields()
  const allAvailableDataSources = ['C', 'E', 'P', 'R'].sort()

  // 根据选择的专业获取对应的数据来源
  const filteredDataSources = selectedSpecialty === 'all' 
    ? allAvailableDataSources 
    : userDataSources

  return (
    <div className="space-y-4">
      {/* 设备和表信息 */}
      <div className="bg-blue-50 p-4 rounded-lg">
        <div className="flex items-center gap-3">
          <Database className="w-6 h-6 text-blue-600" />
          <div>
            <h3 className="font-semibold text-blue-900">{deviceName}</h3>
            <p className="text-sm text-blue-700">
              {getTableTypeName(tableType)} ({tableName}) | 分类码: {classificationCode}
            </p>
          </div>
        </div>
      </div>

      {/* 权限和操作信息 */}
      <div className="flex justify-between items-center">
        <div className="space-y-1">
          <div className="flex items-center gap-2">
            <span className="text-sm font-medium">当前用户:</span>
            <Badge>{user?.full_name} ({user?.role_name})</Badge>
          </div>
          <div className="flex items-center gap-4">
            <span className="text-sm text-gray-600">可编辑字段: {editableCount} / 可见字段: {visibleCount}</span>
          </div>
        </div>
        
        <div className="flex items-center gap-2">
          <select
            value={selectedSpecialty}
            onChange={(e) => setSelectedSpecialty(e.target.value)}
            className="px-3 py-2 border rounded-md text-sm bg-white"
          >
            <option value="all">全部专业</option>
            <option value="my">我的专业</option>
          </select>
          
          <Button
            variant="outline"
            size="sm"
            onClick={() => setShowAllFields(!showAllFields)}
          >
            {showAllFields ? <EyeOff className="h-4 w-4 mr-2" /> : <Eye className="h-4 w-4 mr-2" />}
            {showAllFields ? '隐藏空字段' : '显示所有字段'}
          </Button>
        </div>
      </div>

      {/* 参数编辑表格 */}
      <div className="border rounded-lg">
        {filteredDataSources.length > 0 ? (
          <Tabs defaultValue="all" className="w-full">
            <TabsList className="grid w-full grid-cols-5">
              <TabsTrigger value="all">全部</TabsTrigger>
              {filteredDataSources.slice(0, 4).map(source => (
                <TabsTrigger key={source} value={source}>
                  <div className="flex items-center space-x-1">
                    <span>{getDataSourceName(source)}</span>
                    {!hasDataSourceAccess(source) && (
                      <Lock className="h-3 w-3 text-gray-400" />
                    )}
                  </div>
                </TabsTrigger>
              ))}
            </TabsList>

            {/* 全部标签页 */}
            <TabsContent value="all" className="p-4">
              {fields.filter(f => showAllFields || f.isVisible).length > 0 ? (
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="w-[200px]">字段名称</TableHead>
                      <TableHead className="w-[150px]">描述</TableHead>
                      <TableHead className="w-[80px]">来源</TableHead>
                      <TableHead className="w-[80px]">类型</TableHead>
                      <TableHead className="w-[80px]">单位</TableHead>
                      <TableHead>当前值</TableHead>
                      <TableHead className="w-[80px]">状态</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {fields.filter(f => showAllFields || f.isVisible).map((field) => {
                      const isRequiredField = Boolean(field.is_required) && field.canEdit;
                      const isRequiredAndFilled = isRequiredField && (editData[field.id]?.trim() || '').length > 0;
                      const isRequiredAndMissing = isRequiredField && (editData[field.id]?.trim() || '').length === 0;
                      
                      let rowClassName = "";
                      if (isRequiredAndMissing) {
                        rowClassName = "bg-red-50 border-l-4 border-l-red-400";
                      } else if (isRequiredAndFilled) {
                        rowClassName = "bg-green-50 border-l-4 border-l-green-400";
                      } else if (field.canEdit) {
                        rowClassName = "bg-blue-50";
                      }
                      
                      return (
                        <TableRow key={field.id} className={rowClassName}>
                          <TableCell className="font-medium">
                            <div className="flex items-center gap-2">
                              {field.canEdit && <span className="text-green-600 text-sm">✓</span>}
                              <span className="text-sm">
                                {field.field_name}
                              </span>
                              {Boolean(editData[field.id]?.trim()) && (
                                <CheckCircle className="w-3 h-3 text-green-600 ml-1" />
                              )}
                            </div>
                          </TableCell>
                        <TableCell className="text-xs text-gray-600">
                          {field.field_description}
                        </TableCell>
                        <TableCell>
                          <Badge className={getDataSourceColor(field.data_source)} size="sm">
                            {field.data_source}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <Badge variant="outline" size="sm">{field.data_type}</Badge>
                        </TableCell>
                        <TableCell className="text-xs">{field.measurement_unit}</TableCell>
                        <TableCell>
                          {field.canEdit ? (
                            <Input
                              value={editData[field.id] || ''}
                              onChange={(e) => updateFieldValue(field.id, e.target.value)}
                              placeholder={field.example_description}
                              className="h-8 text-sm"
                            />
                          ) : (
                            <div className="flex items-center space-x-2 text-gray-500">
                              <span className="text-sm">
                                {editData[field.id] || field.parameter_value || '-'}
                              </span>
                              <Lock className="h-3 w-3 text-gray-400" />
                            </div>
                          )}
                        </TableCell>
                        <TableCell>
                          <div className="flex items-center gap-1">
                            {field.canEdit ? (
                              <Badge variant="default" className="bg-green-100 text-green-800 text-xs">
                                可编辑
                              </Badge>
                            ) : (
                              <Badge variant="secondary" className="bg-gray-100 text-gray-600 text-xs">
                                只读
                              </Badge>
                            )}
                          </div>
                        </TableCell>
                      </TableRow>
                      );
                    })}
                  </TableBody>
                </Table>
              ) : (
                <Alert>
                  <AlertCircle className="h-4 w-4" />
                  <AlertDescription>
                    没有可显示的字段数据
                  </AlertDescription>
                </Alert>
              )}
            </TabsContent>

            {/* 各专业标签页 */}
            {filteredDataSources.map(source => {
              const sourceFields = getFieldsByDataSource(source)
              const displayFields = sourceFields.filter(f => showAllFields || f.isVisible)
              
              return (
                <TabsContent key={source} value={source} className="p-4">
                  <div className="mb-4">
                    <h4 className="font-medium text-gray-900">{getDataSourceName(source)}专业字段</h4>
                    <p className="text-sm text-gray-500">
                      {displayFields.filter(f => f.canEdit).length} 可编辑 / {displayFields.length} 总计
                    </p>
                  </div>
                  
                  {displayFields.length > 0 ? (
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead className="w-[200px]">字段名称</TableHead>
                          <TableHead className="w-[150px]">描述</TableHead>
                          <TableHead className="w-[80px]">类型</TableHead>
                          <TableHead className="w-[80px]">单位</TableHead>
                          <TableHead>当前值</TableHead>
                          <TableHead className="w-[80px]">状态</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {displayFields.map((field) => {
                          const isRequiredField = Boolean(field.is_required) && field.canEdit;
                          const isRequiredAndFilled = isRequiredField && (editData[field.id]?.trim() || '').length > 0;
                          const isRequiredAndMissing = isRequiredField && (editData[field.id]?.trim() || '').length === 0;
                          
                          let rowClassName = "";
                          if (isRequiredAndMissing) {
                            rowClassName = "bg-red-50 border-l-4 border-l-red-400";
                          } else if (isRequiredAndFilled) {
                            rowClassName = "bg-green-50 border-l-4 border-l-green-400";
                          } else if (field.canEdit) {
                            rowClassName = "bg-blue-50";
                          }
                          
                          return (
                            <TableRow key={field.id} className={rowClassName}>
                              <TableCell className="font-medium">
                                <div className="flex items-center gap-2">
                                  {field.canEdit && <span className="text-green-600 text-sm">✓</span>}
                                  <span className="text-sm">
                                    {field.field_name}
                                  </span>
                                  {Boolean(field.is_required) && (
                                    <span className={`ml-1 ${isRequiredAndMissing ? 'text-red-600 font-bold' : 'text-red-500'}`}>*</span>
                                  )}
                                  {isRequiredAndFilled && (
                                    <CheckCircle className="w-3 h-3 text-green-600 ml-1" />
                                  )}
                                </div>
                              </TableCell>
                            <TableCell className="text-xs text-gray-600">
                              {field.field_description}
                            </TableCell>
                            <TableCell>
                              <Badge variant="outline" size="sm">{field.data_type}</Badge>
                            </TableCell>
                            <TableCell className="text-xs">{field.measurement_unit}</TableCell>
                            <TableCell>
                              {field.canEdit ? (
                                <Input
                                  value={editData[field.id] || ''}
                                  onChange={(e) => updateFieldValue(field.id, e.target.value)}
                                  placeholder={field.example_description}
                                  className="h-8 text-sm"
                                />
                              ) : (
                                <div className="flex items-center space-x-2 text-gray-500">
                                  <span className="text-sm">
                                    {editData[field.id] || field.parameter_value || '-'}
                                  </span>
                                  <Lock className="h-3 w-3 text-gray-400" />
                                </div>
                              )}
                            </TableCell>
                            <TableCell>
                              <div className="flex items-center gap-1">
                                {field.canEdit ? (
                                  <Badge variant="default" className="bg-green-100 text-green-800 text-xs">
                                    可编辑
                                  </Badge>
                                ) : (
                                  <Badge variant="secondary" className="bg-gray-100 text-gray-600 text-xs">
                                    只读
                                  </Badge>
                                )}
                              </div>
                            </TableCell>
                          </TableRow>
                          );
                        })}
                      </TableBody>
                    </Table>
                  ) : (
                    <Alert>
                      <AlertCircle className="h-4 w-4" />
                      <AlertDescription>
                        该专业没有可显示的字段
                      </AlertDescription>
                    </Alert>
                  )}
                </TabsContent>
              )
            })}
          </Tabs>
        ) : (
          <div className="p-4">
            <Alert>
              <AlertCircle className="h-4 w-4" />
              <AlertDescription>
                没有可用的数据来源
              </AlertDescription>
            </Alert>
          </div>
        )}
      </div>

      {/* 保存按钮和验证状态 */}
      {editableCount > 0 && (
        <div className="pt-4 border-t space-y-3">
          
          {/* 保存按钮 */}
          <div className="flex justify-end gap-2">
            <Button 
              onClick={handleSave} 
              disabled={saving}
              className="flex items-center gap-2"
            >
              {saving ? (
                <>
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                  <span>保存中...</span>
                </>
              ) : (
                <>
                  <Save className="h-4 w-4" />
                  <span>保存参数</span>
                </>
              )}
            </Button>
          </div>
        </div>
      )}
    </div>
  )
}